package com.topscomm.main.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.topscomm.basic.BaseDataSource;
import com.topscomm.tap.mybatis.SqlSessionFactoryBean;

@Configuration
public class DataSourceConfigYwxt {
	@Bean(name = "dataSourceYwxt")
	@ConfigurationProperties(prefix = "spring.datasource.druid.ywxt")
	public DataSource dataSourceYwxt() {
		return new BaseDataSource();
	}

	@Bean(name = "sqlSessionFactoryYwxt")
	public SqlSessionFactory sqlSessionFactoryYwxt(@Qualifier("dataSourceYwxt") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
//		Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath*:config/mybatis/sqlserver/ibatis_*.xml");
		bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:config/mybatis/basic/sqlserver/extend/ibatis_*.xml"));
		bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:config/mybatis/sqlserver/sqlMapConfig.main.xml"));
		bean.setDataSource(dataSource);
		return bean.getObject();
	}

	@Bean(name = "transactionManagerYwxt")
	public DataSourceTransactionManager transactionManagerYwxt(@Qualifier("dataSourceYwxt") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "sqlSessionTemplateYwxt")
	public SqlSessionTemplate sqlSessionTemplateYwxt(@Qualifier("sqlSessionFactoryYwxt") SqlSessionFactory sqlSessionFactory)
			throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
    /**
     * 返回data2数据库的事务
     * @param ds
     * @return
     */
    @Bean(name = "ywxtTransactionManager")
    public DataSourceTransactionManager ywxtTransactionManager(@Qualifier("dataSourceYwxt") DataSource ds){
        return new DataSourceTransactionManager(ds);
    }
}
